﻿using gt.webapi.core.Entity.Common;
using gt.webapi.core.Extensions;
using gt.webapi.core.Repositories;
using System;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Web.Http.Controllers;

namespace gt.webapi.core.Filters.Authority
{
    public class DefaultAuthorizeAttribute : AuthorizeFilterBase
    {
        public DefaultAuthorizeAttribute(IAuthorityRepository authorityRepository)
            : base(authorityRepository)
        {
        }

        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var attrs = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
            bool isAnonymous = attrs.Any(x => x is AllowAnonymousAttribute);
            if (isAnonymous) return true;

            if (actionContext.RequestContext.Principal == null ||
                actionContext.RequestContext.Principal.Identity == null ||
                !actionContext.RequestContext.Principal.Identity.IsAuthenticated) return false;

            var appkey = actionContext.RequestContext.Principal.Identity.Name;

            var controllerActionName = actionContext.Request.GetControllerActionPath();

            if (!m_authorityRepository.CheckAuthority(appkey, controllerActionName)) return false;

            return true;
        }

        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            actionContext.Response = new System.Net.Http.HttpResponseMessage
            {
                StatusCode = System.Net.HttpStatusCode.Unauthorized,
                Content = new StringContent(Constants.ERROR_UNAUTH, Encoding.UTF8, Constants.API_CONTENT_MEDIATPE_TEXT)
            };
        }
    }
}
